<template>
    <div>
      <div>
        <!--      面包屑导航-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>商品管理</el-breadcrumb-item>
          <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!--  卡片视图区域-->
        <el-card class="box-card">
<!--          消息提示框-->
          <el-alert
            title="添加商品消息"
            type="info"
            center
            show-icon
            :closable="false">
          </el-alert>
<!--          步骤条-->
          <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
          </el-steps>
<!--          tab栏区域-->
          <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="70px" label-position='top'>
            <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabLeave" @tab-click="tabClick">
              <el-tab-pane label="基本信息" name="1">
                <el-form-item label="商品名称" prop="goods_name">
                  <el-input v-model="addForm.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" prop="goods_price">
                  <el-input v-model="addForm.goods_price"></el-input>
                </el-form-item>
                <el-form-item label="商品数量" prop="goods_number">
                  <el-input v-model="addForm.goods_number"></el-input>
                </el-form-item>
                <el-form-item label="商品重量" prop="goods_weight">
                  <el-input v-model="addForm.goods_weight"></el-input>
                </el-form-item>
                <el-form-item label="商品分类:" prop="goods_cat">
                  <!--            级联选择框 options: 数据源 props: 配置选项 v-model绑定的是选中的数据，必须是一个数组-->
                  <el-cascader
                    v-model="addForm.goods_cat"
                    :options="parentCateList"
                    :props="cateProps"
                    clearable
                    @change="parentCateChange">
                  </el-cascader>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品参数" name="2">
<!--                渲染表单的Item项-->
                <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
<!--                  复选框-->
                  <el-checkbox-group v-model="item.attr_vals">
                    <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border></el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品属性" name="3">
                <!--                渲染表单的Item项-->
                <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
                  <el-input v-model="item.attr_vals"></el-input>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品图片" name="4">
<!--                headers: 设置上传的请求头部-->
                <el-upload
                  class="upload-demo"
                  action="http://127.0.0.1:8888/api/private/v1/upload"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :headers="handerObj"
                  list-type="picture"
                  :on-success="handerSuccess">
                  <el-button size="small" type="primary" style="margin-left: 5px;">点击上传</el-button>
                </el-upload>
              </el-tab-pane>
              <el-tab-pane label="商品内容" name="5">
<!--                富文本编辑器-->
                <quill-editor v-model="addForm.goods_introduce"></quill-editor>
<!--                添加商品的按钮-->
                <el-button type="primary" class="btnAdd" @click="addGoods">添加商品</el-button>
              </el-tab-pane>
            </el-tabs>
          </el-form>
        </el-card>
        <el-dialog
          title="图片预览"
          :visible.sync="PreviewVisible"
          width="50%">
          <span>
            <img :src="PreviewPath" alt="图片预览" class="previewStyle">
          </span>
        </el-dialog>
      </div>
      </div>
</template>

<style scoped>
  .el-form-item {
    text-align: left;
  }
  .el-checkbox {
    margin: 0 5px 0 0 !important;
  }
  .previewStyle{
    width: 100%;
    height: 100%;
  }
  .btnAdd{
    margin-top: 15px;
  }
</style>

<script>

// 导入lodash,官方建议用_来接收lodash
import _ from 'lodash'

export default {
  data () {
    return {
      // 步骤条激活页
      activeIndex: 0,
      // 添加商品表单数据
      addForm: {
        goods_name: '0',
        goods_price: '0',
        goods_number: '0',
        goods_weight: '0',
        goods_cat: [],
        goods_introduce: '',
        // 添加图片的数组
        pics: [],
        attrs: []
      },
      // 添加表单的验证规则
      addRules: {
        goods_name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        goods_cat: [
          {
            required: true,
            message: '请输入分类列表',
            trigger: 'blur'
          }
        ],
        goods_price: [
          {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }
        ],
        goods_number: [
          {
            required: true,
            message: '请输入商品数量',
            trigger: 'blur'
          }
        ],
        goods_weight: [
          {
            required: true,
            message: '请输入商品重量',
            trigger: 'blur'
          }
        ],
        // eslint-disable-next-line no-dupe-keys
        goods_cat: [
          {
            required: true,
            message: '请输入商品重量',
            trigger: 'blur'
          }
        ]
      },
      // 分类列表
      parentCateList: [],
      // 指定级联选择器的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: false,
        // 触发方式，默认点击触发，hover鼠标移上去即可触发
        expandTrigger: 'hover'
      },
      // 选中的父级id数组
      selectKeys: [],
      // 动态参数列表
      manyTableData: [],
      // 静态属性列表
      onlyTableData: [],
      // 图片上传组件的请求头
      handerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览弹窗开关
      PreviewVisible: false,
      // 图片预览地址
      PreviewPath: ''
    }
  },
  methods: {
    // 获取分类表单
    async showAddCateForm() {
      // 获取所有的二级分类
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取父级分类数据失败！')
      this.parentCateList = res.data
    },
    // 添加分类选择项发生变化触发函数
    parentCateChange() {
      console.log(this.addForm)
      console.log(this.addForm.goods_cat.length)
    },
    // 切换标签页触发 activeName：即将进入的标签页名称，oldName当前标签页名称
    beforeTabLeave(activeName, oldName) {
      if (activeName === '0' || activeName === '1') {
        return true
      } else if (!this.addForm.goods_name) {
        this.$message.error('请先填写商品名称')
        return false
      } else if (!this.addForm.goods_price) {
        this.$message.error('请先填写商品价格')
        return false
      } else if (!this.addForm.goods_weight) {
        this.$message.error('请先填写商品重量')
        return false
      } else if (this.addForm.goods_cat.length === 0) {
        this.$message.error('请先填写商品分类')
        return false
      } else {
        return true
      }
    },
    // 标签点击切换事件
    async tabClick() {
      if (this.activeIndex === '2') {
        // 获取参数列表
        const { data: res } = await this.$http.get(`categories/${this.cat_id}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) return this.$message.error(res.data.msg)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
        console.log(res.data)
      } else if (this.activeIndex === '3') {
        // 获取参数列表
        const { data: res } = await this.$http.get(`categories/${this.cat_id}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) return this.$message.error(res.data.msg)
        this.onlyTableData = res.data
        console.log(res.data)
      }
    },
    // 移除图片事件
    handleRemove(file) {
      console.log(file)
      // 拿到要删除图片的临时路径
      const filePath = file.response.data.tmp_path
      // 找到该路径在addForm.pics中对应的索引值
      const i = this.addForm.pics.findIndex(x => {
        x.pic === filePath
      })
      // 移除对应项
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm.pics)
    },
    // 预览图片事件
    handlePreview(file) {
      this.PreviewVisible = true
      console.log(file)
      this.PreviewPath = file.response.data.url
    },
    // 图片上传成功时的钩子
    handerSuccess(response) {
      // 拼接得到一个图片路径对象
      const picInfo = { pic: response.data.tmp_path }
      this.addForm.pics.push(picInfo)
      console.log(this.addForm.pics)
    },
    async addGoods() {
      this.$refs.addFormRef.validate(async vali => {
        if (!vali) return this.$message.error('请添加必要的表单项')
        // 将goods_cat改成字符串
        // 由于goods_cat被级联选择器双向绑定了，规定了只能是数组，这样会报错
        // this.addForm.goods_cat = this.addForm.goods_cat.join(',')
        // 解决方案：将 goods_cat继续深拷贝（需要安装依赖lodash）
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        this.manyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
          this.addForm.attrs.push(newInfo)
        })
        this.onlyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        console.log(form)
        // 发起请求，添加商品（商品名称必须是唯一的）
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }
  },
  created () {
    this.showAddCateForm()
  },
  computed: {
    cat_id() {
      return this.addForm.goods_cat[2]
    }
  }
}
</script>
